package org.goldenmock.web.server;

import org.easymock.EasyMock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author Robin Wagenaar
 * @author Arjen van Staalduinen
 */
public class HttpEasymockServer implements HttpServerInterface {

    private static final Logger logger = LoggerFactory.getLogger(HttpServerInterface.class);

    private HttpServerInterface delegate;

    public HttpEasymockServer() {
        delegate = EasyMock.createMock(HttpServerInterface.class);
    }

    public HttpServerInterface getMock() {
        return delegate;
    }

    @Override
    public EasyHttpResponse handle(EasyHttpRequest httpRequest) {
        try {
            return delegate.handle(httpRequest);
        } catch (AssertionError e) {
            logger.error("AssertionError bij handle httpRequest: " + httpRequest, e);
            return createHttpResponseForException(404, e);
        } catch(Exception e){
            logger.error("AssertionError bij handle httpRequest: " + httpRequest, e);
            return createHttpResponseForException(500, e);
        }
    }

    protected EasyHttpResponse createHttpResponseForException(Integer httpCode, Throwable e){
        String content = String.format("Server error: "+ e.getMessage());
        return new EasyHttpResponseBuilder()
                .withHttpCode(httpCode)
                .withContentType("text/plain")
                .withContent(content);
    }
}
